<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="时间范围" prop="datePicker">
              <el-date-picker v-model="datePicker" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" @change="changeTimer" />
            </el-form-item>
            <el-form-item label="推广链接id" prop="referralLinkId">
              <el-input v-model="queryParams.referralLinkId" placeholder="请输入推广链接id" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="广告主id" prop="thirdAdvertiserId">
              <el-input v-model="queryParams.thirdAdvertiserId" placeholder="请输入广告主id" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="短剧名称" prop="dramaTitle">
              <el-input v-model="queryParams.dramaTitle" placeholder="请输入短剧名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <!--            <el-form-item label="部门" prop="deptId">-->
            <!--              <el-select v-model="queryParams.deptId" clearable placeholder="请选择部门">-->
            <!--                <el-option v-for="(item, key) in departList" :key="key" :value="item.deptId"-->
            <!--                           :label="item.deptName"></el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->

            <el-form-item label="投手名称" prop="createName">
              <el-input v-model="queryParams.createName" placeholder="请输入投手名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="推广链接类型" prop="referralLinkType">
              <el-select v-model="queryParams.referralLinkType" clearable placeholder="请选择推广链接类型">
                <el-option v-for="(item, key) in appTypeList" :key="key" :value="item.type" :label="item.desc"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="小程序平台" prop="appType">
              <el-select v-model="queryParams.appType" clearable placeholder="请选择小程序平台">
                <el-option v-for="(item, key) in linkTypeList" :key="key" :value="item.type" :label="item.desc"></el-option>
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="推广名称" prop="referralLinkName">
              <el-input v-model="queryParams.referralLinkName" placeholder="请输入推广名称" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->

            <el-form-item label="广告主名称" prop="thirdAdvertiserName">
              <el-input v-model="queryParams.thirdAdvertiserName" placeholder="请输入广告主名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <!--            <el-form-item label="短剧id" prop="dramaId">-->
            <!--              <el-input v-model="queryParams.dramaId" placeholder="请输入短剧id" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="短剧名称" prop="dramaTitle">-->
            <!--              <el-input v-model="queryParams.dramaTitle" placeholder="请输入短剧名称" clearable-->
            <!--                        @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->

            <el-form-item style="width: auto">
              <div class="btns">
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>

                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:advertiserEverydayCost:export']"
                  >导出
                </el-button>
              </div>

              <div class="btns">
                <el-button type="primary" icon="RefreshRight" @click="handleSyncOrder()" v-hasPermi="['oce:advertiserEverydayCost:syncCost']"
                  >校正消耗
                </el-button>
                <el-button type="primary" icon="RefreshRight" @click="handleSyncCost()" v-hasPermi="['oce:advertiserEverydayCost:syncOrder']"
                  >校正充值
                </el-button>
                <el-button type="primary" icon="Plus" @click="openAiAdd" v-hasPermi="['oce:advertiserEverydayCostIaa:create']">一键新建 </el-button>
                <el-button type="primary" @click="queryAiList" v-hasPermi="['oce:advertiserEverydayCostIaa:create']">新建历史查询 </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <div class="relative overauto" style="min-height: 100px">
        <div class="setting-btn absolute right-[0] top-[0]">
          <el-button icon="Setting" @click="openList()" />
        </div>

        <listView :list="sum" :show="true" @liseViewChange="liseViewChange" />
      </div>

      <div class="setting-btn">
        <el-button icon="Setting" @click="openThead()" />
      </div>

      <el-table
        v-loading="loading"
        :data="advertiserEverydayCostList"
        @sort-change="sortChangeHandel"
        :max-height="computeHeight()"
        @selection-change="handleSelectionChange"
        class="custom-table-height"
        row-class-name="scale"
        cell-class-name="scale"
        header-row-class-name="scale"
      >
        <el-table-column :fixed="useAppStore().windowWidth > 800 ? true : false" label="投放账户" prop="referralLinkName" :minWidth="240">
          <template #default="{ row }">
            <div class="content-wrap">
              <div>
                广告主ID:
                <el-text type="danger">
                  <span class="cursor-pointer underline" v-copyText="row.thirdAdvertiserId">{{ row.thirdAdvertiserId }}</span>
                </el-text>
              </div>
              <div>
                链接ID:
                <el-text type="danger">
                  <span class="cursor-pointer underline" v-copyText="row.referralLinkId">{{ row.referralLinkId }}</span>
                </el-text>
              </div>
              <div>
                <span>{{ row.thirdAdvertiserName || '-' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :fixed="useAppStore().windowWidth > 800 ? true : false"
          :label="`短剧名称`"
          prop="dramaTitle"
          :minWidth="150 * 0.75"
        ></el-table-column>
        <el-table-column :fixed="useAppStore().windowWidth > 800 ? true : false" label="投手" prop="createName" minWidth="90"></el-table-column>

        <el-table-column
          :label="item.name"
          :prop="item.code"
          :width="120 * 0.75"
          v-for="(item, index) in tableTh"
          :key="index"
          :sortable="!item.disableSort ? 'custom' : false"
        >
          <template #default="{ row }">
            <span v-if="item.format && item.code != 'costHoursSpeed'">{{ parseFloat(row[item.code]).toFixed(item.fixed || 2) }}</span>
            <span v-if="item.code != 'costHoursSpeed' && !item.format">{{ row[item.code] }}{{ item.percent ? '%' : '' }}</span>

            <span
              v-if="item.code == 'costHoursSpeed'"
              @click="clickHandle(row, 0)"
              v-hasPermi="['oce:everydayCostHours:listHours']"
              style="color: var(--el-color-danger); text-decoration: underline; cursor: pointer"
            >
              {{ row.costHoursSpeed }}
            </span>
            <span
              v-if="item.code == 'costHoursSpeed'"
              @click="clickHandle(row, 1)"
              v-hasPermi="['oce:everydayCostHours:listOrder']"
              style="margin-left: 6px; color: var(--el-color-primary); text-decoration: underline; cursor: pointer"
              >(趋势)</span
            >
          </template>
        </el-table-column>

        <!--        <el-table-column label="观看广告次数" prop="advertNum" width="120" />-->

        <!--        <el-table-column label="平均ecpm" prop="avgEcpm" width="120">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.avgEcpm) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="最大ecpm" prop="maxEcpm" width="120">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.maxEcpm) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <!--        <el-table-column label="账户消耗" prop="cost" width="120" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.cost) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="时速" prop="costHoursSpeed" minWidth="130" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span-->
        <!--              @click="clickHandle(row, 0)"-->
        <!--              v-hasPermi="['oce:everydayCostHours:listHours']"-->
        <!--              style="color: var(&#45;&#45;el-color-danger); text-decoration: underline; cursor: pointer"-->
        <!--            >-->
        <!--              {{ row.costHoursSpeed }}-->
        <!--            </span>-->
        <!--            <span-->
        <!--              @click="clickHandle(row, 1)"-->
        <!--              v-hasPermi="['oce:everydayCostHours:listOrder']"-->
        <!--              style="margin-left: 6px; color: var(&#45;&#45;el-color-primary); text-decoration: underline; cursor: pointer"-->
        <!--              >(趋势)</span-->
        <!--            >-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <!--        <el-table-column label="新增充值" prop="thatdayRegisterTotalAmount" minWidth="110" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.thatdayRegisterTotalAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="当日充值" prop="thatdayTotalAmount" minWidth="110" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.thatdayTotalAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <!--        <el-table-column label="新增分成金额" prop="thatdayRegisterDividendAmount" minWidth="140" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.thatdayRegisterDividendAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="当日充值分成" minWidth="140" prop="thatdayDividendAmount" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.thatdayDividendAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="新增广告分成" prop="iaaRegisterDividendAmount" minWidth="150" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.iaaRegisterDividendAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="当日广告分成" prop="iaaDividendAmount" minWidth="150" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.iaaDividendAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="利润" prop="thatdayProfitAmount" minWidth="100" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.thatdayProfitAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="回本率" prop="extRecoveryRate" minWidth="120" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ row.extRecoveryRate }}%</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="千展成本" prop="avgShowCost" width="120" sortable="custom"></el-table-column>-->
        <!--        <el-table-column label="展示数" prop="show" width="100" sortable="custom"></el-table-column>-->
        <!--        <el-table-column label="点击数" prop="click" width="100" sortable="custom"></el-table-column>-->
        <!--        <el-table-column label="点击成本" prop="avgClickCost" width="110" sortable="custom"></el-table-column>-->
        <!--        <el-table-column label="点击率" prop="ctr" width="100" sortable="custom" :formatter="(row) => `${row.ctr}%`"></el-table-column>-->
        <!--        <el-table-column label="转化数" prop="convert" minWidth="100" sortable="custom"></el-table-column>-->
        <!--        <el-table-column label="转化成本" prop="convertCost" minWidth="110" sortable="custom"></el-table-column>-->
        <!--        <el-table-column-->
        <!--          label="转化率"-->
        <!--          prop="convertRate"-->
        <!--          minWidth="110"-->
        <!--          sortable="custom"-->
        <!--          :formatter="(row) => `${row.convertRate}%`"-->
        <!--        ></el-table-column>-->
        <!--        <el-table-column label="付费人数" prop="thatdayPaidUseNum" minWidth="110" sortable="custom"></el-table-column>-->
        <!--        <el-table-column label="付费次数" prop="thatdayPaidTotalNum" minWidth="110" sortable="custom"></el-table-column>-->
        <!--        <el-table-column label="付费成本" prop="extPayCost" minWidth="110" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ row.extPayCost }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="客单价" prop="extAvgPrice" minWidth="110" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ row.extAvgPrice }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="回传率" prop="" minWidth="90" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            {{ row.returnRate }}%-->
        <!--            &lt;!&ndash; <span>{{ convertToPercentage(row.convert, row.thatdayPaidUseNum) }}</span> &ndash;&gt;-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <!--        <el-table-column label="新增广告收益" prop="iaaRegisterTotalAmount" minWidth="140" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.iaaRegisterTotalAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="当日广告收益" prop="iaaTotalAmount" minWidth="140" sortable="custom">-->
        <!--          <template #default="{ row }">-->
        <!--            <span>{{ formatPrice(row.iaaTotalAmount) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column fixed="right" label="推荐" prop="score">
          <template #default="{ row }">
            <el-tooltip effect="dark" placement="top">
              <template #content>
                <div v-if="row.score?.messages">
                  <div class="time">{{ row.score.time }}</div>
                  <div v-html="row.score?.messages"></div>
                </div>
                <div v-else>无</div>
              </template>
              <div class="flex flex-col cursor-pointer taglist" v-if="row.score?.results">
                <div class="tags" v-for="(item, index) in row?.score?.results" :key="index">{{ item }}</div>
              </div>
              <div class="" v-else>-</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="100" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <el-button
                link
                type="primary"
                icon="RefreshRight"
                @click="handleSyncOrder(scope.row)"
                v-hasPermi="['oce:advertiserEverydayCost:syncCost']"
                >校正消耗
              </el-button>
            </div>
            <div>
              <el-button
                link
                type="primary"
                icon="RefreshRight"
                @click="handleSyncCost(scope.row)"
                v-hasPermi="['oce:advertiserEverydayCost:syncOrder']"
                >校正充值
              </el-button>
            </div>
            <div>
              <el-button link type="primary" icon="Plus" @click="handleAiAdd(scope.row)" v-hasPermi="['oce:advertiserEverydayCostIaa:add']"
                >一键新增
              </el-button>
            </div>
            <div>
              <el-button
                link
                type="primary"
                icon="Refresh"
                @click="handleAiUpdate(scope.row)"
                v-hasPermi="['oce:advertiserEverydayCostIaa:batchUpdate']"
                >批量修改
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <Cesaie ref="cesaieRef" />
    <AllCesaie ref="allCesaieRef" />
    <Trend ref="trendRef" />
    <AllTrendRef ref="allTrendRef" />

    <THead :is-show-modal="isShowModal" :thead="allList" @submit="onSubmit" @close="onClose" />

    <list-head :is-show-modal="isShowModalList" :thead="allListList" @submit="onSubmitList" @close="onCloseList" />

    <AiAdd
      ref="aiAddRef"
      :show="aiAddVisible"
      :appTypeList="appTypeList"
      :curRow="curRow"
      :model="adAddModel"
      @update:visible="aiAddVisible = $event"
      @update:refresh="getList"
    />
    <AiUpdate ref="aiUpadteRef" :show="aiUpdateVisible" :curRow="curRow" @update:visible="aiUpdateVisible = $event" @update:refresh="getList" />
  </div>
</template>

<script setup name="AdvertiserEverydayCost" lang="ts">
import { listAdvertiserEverydayCost } from '@/api/oce/advertiserEverydayCost';
import { getListLinkType, getListAppType, syncOrder, syncCost } from '@/api/stock';
import { AdvertiserEverydayCostVO, AdvertiserEverydayCostQuery, AdvertiserEverydayCostForm } from '@/api/oce/advertiserEverydayCost/types';
import { formatPrice, formatYmd, getFirstLetter } from '@/utils';
import Cesaie from './components/cesaie.vue';
import AllCesaie from './components/allCesaie.vue';
import Trend from './components/trend.vue';
import THead from '@/components/THead/index.vue';

import AiAdd from './components/aiAdd.vue';
import AiUpdate from './components/aiUpdate.vue';
import { getMaticPlacementScores, aiTest } from '@/api/ai';

import AllTrendRef from './components/allTrend.vue';
import useAppStore from '@/store/modules/app';

import dayjs from 'dayjs';
import ListHead from '@/components/Listhead/index.vue';
import useUserStore from '@/store/modules/user';
const route = useRoute();
const userStore = useUserStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const showTxt = '这是第一行<br>这是第二行';

const aiAddRef = ref(null);

const advertiserEverydayCostList = ref<AdvertiserEverydayCostVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const cesaieRef = ref<InstanceType<typeof Cesaie>>();
const allCesaieRef = ref<InstanceType<typeof AllCesaie>>();
const trendRef = ref<InstanceType<typeof Trend>>();
const allTrendRef = ref<InstanceType<typeof AllTrendRef>>();
const queryFormRef = ref<ElFormInstance>();
const advertiserEverydayCostFormRef = ref<ElFormInstance>();

const isShowModal = ref(false);

const curRow = ref();

const adAddModel = ref('add');

const aiAddVisible = ref(false);

const aiUpdateVisible = ref(false);

let allList = ref([
  {
    name: '回本率',
    code: 'extRegisterRecoveryRate',
    percent: true,
    isCheck: true
  },
  {
    name: '当日LTV',
    code: 'attributionMicroGame0dLtv',
    format: true,
    fixed: 2,
    isCheck: true
  },
  {
    name: '当日广告变现ROI',
    code: 'attributionMicroGame0dRoi',
    format: true,
    fixed: 2,
    isCheck: true
  },

  {
    name: '激励点击金额',
    code: 'ecpmCost',
    format: true,
    fixed: 5,
    disableSort: true,
    isCheck: true
  },
  {
    name: '观看广告次数',
    code: 'advertNum',
    disableSort: true,
    isCheck: true
  },
  {
    name: '平均ecpm',
    code: 'avgEcpm',
    format: true,
    disableSort: true,
    isCheck: true
  },
  {
    name: '最大ecpm',
    code: 'maxEcpm',
    format: true,
    disableSort: true,
    isCheck: true
  },
  {
    name: '账户消耗',
    code: 'cost',
    format: true,
    isCheck: true
  },
  {
    name: '时速',
    code: 'costHoursSpeed',
    isCheck: true
  },
  {
    name: '充值',
    code: 'thatdayRegisterTotalAmount',
    format: true,
    isCheck: true
  },

  {
    name: '分成金额',
    code: 'thatdayRegisterDividendAmount',
    format: true,
    isCheck: true
  },
  {
    name: '广告分成',
    code: 'iaaRegisterDividendAmount',
    format: true,
    isCheck: true
  },
  {
    name: '利润',
    code: 'thatdayRegisterProfitAmount',
    format: true,
    isCheck: true
  },

  {
    name: '千展成本',
    code: 'avgShowCost',
    isCheck: true
  },
  {
    name: '展示数',
    code: 'show',
    isCheck: true
  },
  {
    name: '点击数',
    code: 'click',
    isCheck: true
  },
  {
    name: '点击成本',
    code: 'avgClickCost',
    format: true,
    isCheck: true
  },
  {
    name: '点击率',
    code: 'ctr',
    percent: true,
    isCheck: true
  },
  {
    name: '转化数',
    code: 'convert',
    isCheck: true
  },
  {
    name: '转化成本',
    code: 'convertCost',
    format: true,
    isCheck: true
  },
  {
    name: '转化率',
    code: 'convertRate',
    percent: true,
    isCheck: true
  },
  {
    name: '付费人数',
    code: 'thatdayPaidUseNum',
    isCheck: true
  },
  {
    name: '付费次数',
    code: 'thatdayPaidTotalNum',
    isCheck: true
  },
  {
    name: '付费成本',
    code: 'extPayCost',
    format: true,
    isCheck: true
  },
  {
    name: '客单价',
    code: 'extAvgPrice',
    format: true,
    isCheck: true
  },
  {
    name: '回传率',
    code: 'returnRate',
    percent: true,
    isCheck: true
  },
  {
    name: '广告收入',
    code: 'iaaRegisterTotalAmount',
    format: true,
    isCheck: true
  }
]);

const tableTh = ref(JSON.parse(JSON.stringify(allList.value)));

const allListList = ref([]);
const listTh = ref([]);
const isShowModalList = ref(false);

const initFormData: AdvertiserEverydayCostForm = {
  advertiserCostId: undefined,
  referralLinkId: undefined,
  referralLinkType: undefined,
  referralLinkName: undefined,
  thirdAdvertiserAppCode: undefined,
  thirdAdvertiserId: undefined,
  thirdAdvertiserName: undefined,
  thatdayTimestamp: undefined,
  thatdayDate: undefined,
  thatdayTotalAmount: undefined,
  thatdayDividendAmount: undefined,
  thatdayProfitAmount: undefined,
  thatdayPaidTotalNum: undefined,
  thatdayPaidUseNum: undefined,
  thatdayRegisterTotalAmount: undefined,
  thatdayRegisterDividendAmount: undefined,
  iaaTotalAmount: undefined,
  iaaDividendAmount: undefined,
  iaaProfitAmount: undefined,
  iaaRegisterTotalAmount: undefined,
  iaaRegisterDividendAmount: undefined,
  dramaTitle: undefined,
  cost: undefined,
  show: undefined,
  avgShowCost: undefined,
  click: undefined,
  avgClickCost: undefined,
  ctr: undefined,
  convert: undefined,
  convertCost: undefined,
  convertRate: undefined,
  active: undefined,
  activeCost: undefined,
  activeRate: undefined,
  activePay: undefined,
  activePayCost: undefined,
  activePayRate: undefined,
  gamePayCount: undefined,
  gamePayCost: undefined,
  costHoursSpeed: undefined,
  createName: undefined,
  appType: undefined,
  deptId: undefined,
  extRecoveryRate: undefined,
  extAvgPrice: undefined,
  dramaId: undefined,
  startDate: undefined,
  endDate: undefined,
  extPayCost: undefined
};
const data = reactive<PageData<AdvertiserEverydayCostForm, AdvertiserEverydayCostQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    iaaFlag: 1,
    deptId: undefined,
    referralLinkId: undefined,
    referralLinkType: undefined,
    referralLinkName: undefined,
    thirdAdvertiserAppCode: undefined,
    thirdAdvertiserId: undefined,
    thirdAdvertiserName: undefined,
    thatdayTimestamp: undefined,
    thatdayDate: undefined,
    thatdayTotalAmount: undefined,
    thatdayDividendAmount: undefined,
    thatdayProfitAmount: undefined,
    thatdayPaidTotalNum: undefined,
    thatdayPaidUseNum: undefined,
    thatdayRegisterTotalAmount: undefined,
    thatdayRegisterDividendAmount: undefined,
    iaaTotalAmount: undefined,
    iaaDividendAmount: undefined,
    iaaProfitAmount: undefined,
    iaaRegisterTotalAmount: undefined,
    iaaRegisterDividendAmount: undefined,
    dramaTitle: undefined,
    cost: undefined,
    show: undefined,
    avgShowCost: undefined,
    click: undefined,
    avgClickCost: undefined,
    ctr: undefined,
    convert: undefined,
    convertCost: undefined,
    convertRate: undefined,
    active: undefined,
    activeCost: undefined,
    activeRate: undefined,
    activePay: undefined,
    activePayCost: undefined,
    activePayRate: undefined,
    gamePayCount: undefined,
    gamePayCost: undefined,
    costHoursSpeed: undefined,
    createName: undefined,
    appType: undefined,
    extRecoveryRate: undefined,
    extAvgPrice: undefined,
    extPayCost: undefined,
    dramaId: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
    params: {}
  },
  rules: undefined
});
const datePicker = ref<any>([dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]);

const { queryParams, form } = toRefs(data);
const sum = ref([]);

const windowWidth = ref(document.body.clientWidth);
// import.meta.env.VITE_BASE_AI_URL
const getScores = async (data) => {
  try {
    const response = await fetch(import.meta.env.VITE_BASE_AI_URL + 'automatic_placement/inner/scores', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ advertiser_ids: data })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json(); // 解析 JSON 数据
    return result; // 返回结果
  } catch (error) {
    throw error; // 抛出错误，供调用时处理
  }
};

/** 查询巨量广告主每日消耗记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAdvertiserEverydayCost(queryParams.value);
  advertiserEverydayCostList.value = res.rows;
  let sums = res.sum || [];
  //查询广告分数
  let advertiser_ids = [];
  advertiserEverydayCostList.value.map((item) => {
    advertiser_ids.push(Number(item.thirdAdvertiserId));
  });

  // const res2 = await getMaticPlacementScores({ 'advertiser_ids': advertiser_ids });
  // console.log(res2, 'res2');
  (async () => {
    try {
      const scores = await getScores(advertiser_ids);
      advertiserEverydayCostList.value.map((item, index) => {
        item.score = scores.data[item.thirdAdvertiserId] ? scores.data[item.thirdAdvertiserId] : null;
      });
    } catch (error) {}
  })();
  // getScroes(advertiser_ids);

  allListList.value = JSON.parse(
    JSON.stringify(
      sums.filter((item) => {
        if (!item.flag) {
          return true;
        } else {
          //获取用户权限
          let permissions = userStore.permissions;
          if (permissions.indexOf(`oce:advertiserEverydayCost:${getFirstLetter(item.desc)}`) != -1 || permissions.indexOf('*:*:*') != -1) {
            return true;
          } else {
            return false;
          }
        }

        //return !item.flag;
      })
    )
  );
  computeAllListList();
  // sum.value = res.sum || [];
  total.value = res.total;
  loading.value = false;
};

const appTypeList = ref([]);
const linkTypeList = ref([]);
/** 类型列表 */
const getAxios = async () => {
  getListLinkType().then((res) => {
    appTypeList.value = res.data;
  });
  getListAppType().then((res) => {
    linkTypeList.value = res.data;
  });

  // getListDepartment({status:'0'}).then((res) => {
  //   departList.value = res.data;
  // });
};

const changeTimer = (e) => {
  queryParams.value.startDate = e ? formatYmd(e[0]) : '';
  queryParams.value.endDate = e ? formatYmd(e[1]) : '';
};

const clickHandle = (row, type) => {
  switch (type) {
    case 0:
      cesaieRef.value?.show({
        referralLinkId: row.referralLinkId,
        thatdayTimestamp: row.thatdayTimestamp
      });
      break;
    case 1:
      trendRef.value?.show({
        referralLinkId: row.referralLinkId,
        thatdayTimestamp: row.thatdayTimestamp
      });
      break;
    default:
      break;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  datePicker.value = [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')];
  queryParams.value.startDate = datePicker.value[0];
  queryParams.value.endDate = datePicker.value[1];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdvertiserEverydayCostVO[]) => {
  ids.value = selection.map((item) => item.advertiserCostId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const sortChangeHandel = ({ order, prop }) => {
  queryParams.value.orderByColumn = prop;
  queryParams.value.isAsc = order === 'ascending' ? 'asc' : 'desc';
  getList();
};

/** 校正消耗 */
const handleSyncOrder = async (row?: any) => {
  await proxy?.$modal.confirm('是否校正消耗？');
  await syncCost({
    advertiserCostId: row?.advertiserCostId || '0',
    iaaFlag: queryParams.value.iaaFlag,
    ...queryParams.value
  });
  getList();
};

/** 校正充值 */
const handleSyncCost = async (row?: any) => {
  await proxy?.$modal.confirm('是否校正充值？');
  await syncOrder({
    iaaFlag: queryParams.value.iaaFlag,
    advertiserCostId: row?.advertiserCostId || '0',
    ...queryParams.value
  });
  getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oce/advertiserEverydayCost/export',
    {
      ...queryParams.value
    },
    `advertiserEverydayCost_${new Date().getTime()}.xlsx`
  );
};
const liseViewChange = (data) => {
  switch (data) {
    case 'ss':
      allCesaieRef.value?.show(queryParams.value);
      break;
    case 'qs':
      allTrendRef.value?.show(queryParams.value);
      break;
    default:
      break;
  }
};

const computeHeight = () => {
  let baseHeight = 900;
  let totalHeight = document.body.clientHeight;
  if (useAppStore().windowWidth > 500) {
    //计算表格的 高度
    return totalHeight - 150;
  } else {
    return baseHeight;
  }
};

onMounted(() => {
  let iaa = localStorage.getItem('iaa5');
  if (iaa) {
    // tableTh.value = JSON.parse(iaa);
    const result = JSON.parse(iaa)
      .map((itemA) => {
        const itemB = tableTh.value.find((itemB) => itemB.code === itemA.code);
        return itemB ? { ...itemA, ...itemB } : null; // 合并属性
      })
      .filter((item) => item !== null);
    tableTh.value = result;
    computeAllList();
  }

  if (route.query.referralLinkId) {
    queryParams.value.referralLinkId = route.query.referralLinkId as string;
    // datePicker.value = ['', ''];
  }
  // else {
  //
  //  }
  queryParams.value.startDate = datePicker.value[0];
  queryParams.value.endDate = datePicker.value[1];

  getList();
  getAxios();
});

const openList = () => {
  isShowModalList.value = true;
};

const openThead = () => {
  isShowModal.value = true;
};

const onClose = () => {
  isShowModal.value = false;
};

const onCloseList = () => {
  isShowModalList.value = false;
};

const onSubmit = (data) => {
  //本地记录
  localStorage.setItem('iaa5', JSON.stringify(data));

  tableTh.value = data;

  computeAllList();
  onClose();
};

const onSubmitList = (data) => {
  //本地记录
  localStorage.setItem('iaaList5', JSON.stringify(data));
  listTh.value = data;
  computeAllListList();
  onCloseList();
};

const computeAllList = () => {
  allList.value.forEach((item) => {
    let zzw = tableTh.value.find((at) => {
      return at.code == item.code;
    });

    if (zzw) {
      item.isCheck = true;
    } else {
      item.isCheck = false;
    }
  });
};

const computeAllListList = () => {
  let iaaList = localStorage.getItem('iaaList5');

  let lis = JSON.parse(JSON.stringify(allListList.value));

  //设置默认选中
  lis.forEach((item) => {
    item.isCheck = true;
  });

  if (iaaList) {
    let list = JSON.parse(iaaList);

    lis.forEach((item) => {
      let it = list.find((at) => {
        return at.desc == item.desc;
      });

      if (it) {
        it.type = item.type;
        it.flag = item.flag;
        item.isCheck = true;
      } else {
        item.isCheck = false;
      }
    });

    sum.value = list;
  } else {
    sum.value = JSON.parse(JSON.stringify(allListList.value));
  }
  allListList.value = lis;
};

watch(
  () => route.query.referralLinkId,
  () => {
    queryParams.value.referralLinkId = route.query.referralLinkId as string;

    let referralLinkId = route.query.referralLinkId as string;
    queryParams.value.referralLinkId = referralLinkId;
    // if(){
    //
    // }
    // datePicker.value = ['', ''];
    // queryParams.value.startDate = datePicker.value[0];
    // queryParams.value.endDate = datePicker.value[1];

    getList();
  }
  // { deep: true }
);

/**
 * 打开AI添加弹窗
 */
const openAiAdd = () => {
  adAddModel.value = 'add';
  aiAddVisible.value = true;
};

const handleAiAdd = (row) => {
  curRow.value = row;
  adAddModel.value = 'edit';
  aiAddVisible.value = true;
};
const handleAiUpdate = (row) => {
  curRow.value = row;
  aiUpdateVisible.value = true;
};

const queryAiList = () => {
  aiAddRef.value?.resultBoxShow();
  setTimeout(() => {
    aiAddRef.value?.userQuery();
  }, 500);
};
</script>

<style lang="less">
.btns {
  margin-left: 12px;
}
.setting-btn {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}

.custom-table-height .el-table__row {
  height: 50px; /* 设置行高为50px */
}

.custom-table-height .el-table__cell {
  padding: 5px !important;
}

@media screen and (max-width: 500px) {
  .btns {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 12px;
  }
}

.overauto {
  overflow-x: auto;
}
:deep(.el-tooltip__content) {
  white-space: pre-line; /* 允许换行 */
}
</style>
